package com.qg.oss.core.minio.client;

import com.qg.oss.core.CommonClient;
import com.qg.oss.core.minio.config.MinIOProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author QG
 * @Date 2023/7/11 16:13
 * @description
 **/
//@Component
@Slf4j
public class MinIOClient implements CommonClient {

    private static final String PREFIX = "http://";

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinIOProperties minIOProperties;

    @Override
    public String uploadFile(String fileName, String bucketName, byte[] bytes, String folder, String objectName) {
        String fileMd5 = DigestUtils.md5Hex(bytes);
        if (StringUtils.isEmpty(objectName)) {
            objectName = fileMd5 + fileName.substring(fileName.lastIndexOf("."));
        }
        //设置文件存储路径
        if (StringUtils.isEmpty(folder)) {
            folder = getFolder(new Date(), true, true, true);
        } else if (!folder.contains("/")) {
            folder = folder + "/";
        }
        folder = folder + objectName;
        //上传文件
        try {
            uploadFileToOSS(bytes, bucketName, objectName);
            //TODO 返回文件路径
            return PREFIX + minIOProperties.getEndpoint() + bucketName + "/" + objectName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传异常");
        }
    }


    @Override
    public void uploadFileToOSS(byte[] bytes, String bucketName, String objectName) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                //InputStream stream, long objectSize 对象大小, long partSize 分片大小(-1表示5M,最大不要超过5T，最多10000)
                .stream(byteArrayInputStream, byteArrayInputStream.available(), -1)
                .build();
        //上传到minio
        try {
            minioClient.putObject(putObjectArgs);
        } catch (Exception e) {
            log.debug("上传文件到文件系统出错:{}", e.getMessage());
            throw new RuntimeException("MinIO上传文件异常");
        }
    }

    private String getFolder(Date date, boolean year, boolean month, boolean day) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd");
        String dateFormat = format.format(new Date());
        String[] split = dateFormat.split(":");
        StringBuilder sb = new StringBuilder();
        if (year) {
            sb.append(split[0]);
            sb.append("/");
        }
        if (month) {
            sb.append(split[1]);
            sb.append("/");
        }
        if (day) {
            sb.append(split[2]);
            sb.append("/");
        }
        return sb.toString();
    }
}
